//
//  XTXChatViewController.m
//  xiaotianxin
//
//  Created by XYC on 2019/6/11.
//  Copyright © 2019 XYC. All rights reserved.
//

#import "XTXChatViewController.h"
#import "XTXChatCell.h"
#import "XTXAccusationView.h"
#import "XTXXQViewController.h"
#import <AVFoundation/AVFoundation.h>

@interface XTXChatViewController ()<UITableViewDataSource,UITableViewDelegate>
{
    CGFloat temWidth;
    CGFloat temHeight;
}
@property (nonatomic, strong) UIButton *guanzhuBtn;
@property (nonatomic, assign) BOOL tmpBol;
@property (nonatomic, strong) NSMutableArray *chatArr;
@property (nonatomic, assign) NSInteger pageCount;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UITextField *textField;

@end

@implementation XTXChatViewController

- (NSMutableArray *)chatArr
{
    if (!_chatArr) {
        _chatArr = [NSMutableArray array];
    }
    return _chatArr;
}

- (NSUInteger)getDurationWithVideoLocalPath:(NSString *)videoLocalPath {
    if (!videoLocalPath || videoLocalPath.length == 0) {
        NSAssert(NO, @"videoPath is error");
        return 0;
    }
    NSDictionary *opts = [NSDictionary dictionaryWithObject:@(NO) forKey:AVURLAssetPreferPreciseDurationAndTimingKey];
    AVURLAsset *urlAsset = [AVURLAsset URLAssetWithURL:[NSURL fileURLWithPath:videoLocalPath] options:opts];     //初始化视频媒体文件
    NSUInteger second = 0;
    second = ceilf((double)urlAsset.duration.value / (double)urlAsset.duration.timescale); // 获取视频总时长,单位秒
    [self getSizeOfVideoAsset:nil];
    return second;
}


-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.chatArr.count;
}
- (CGSize)getSizeOfVideoAsset:(AVAsset*)videoAsset {
    if (videoAsset && [videoAsset tracksWithMediaType:AVMediaTypeVideo].count>0) {
        AVAssetTrack *track = [[videoAsset tracksWithMediaType:AVMediaTypeVideo] firstObject];
        CGSize dimensions = CGSizeMake(fabs(CGSizeApplyAffineTransform(track.naturalSize, track.preferredTransform).width), fabs(CGSizeApplyAffineTransform(track.naturalSize, track.preferredTransform).height));
        return dimensions;
    } else {
        return CGSizeMake(0, 0);
    }
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString * reuseIdentifier = @"Identifier";
    XTXChatCell * cell = [[XTXChatCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:reuseIdentifier];
    cell.backgroundColor = UIColor.whiteColor;
    if (cell == nil) {
        cell = [[XTXChatCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:reuseIdentifier];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.liaotianLabelTime.text = [XTXGongTool shijianchushihua:self.chatArr[indexPath.row][@"itime"]];
    if ([self.chatArr[indexPath.row][@"send"] integerValue] == 1) {
        [cell.xitongImageView02 sd_setImageWithURL:[NSURL URLWithString:XTXGongTool.share.useMode.headimage] placeholderImage:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
        }];
        cell.xitongImageView02.sd_layout.rightSpaceToView(cell.contentView, iOS_frame_width(30)).widthIs(40).heightIs(40).bottomSpaceToView(cell.contentView, iOS_frame_height(0));
        cell.xitongImageView.sd_layout.widthIs(iOS_frame_width(14)).heightIs(iOS_frame_height(24)).centerYEqualToView(cell.xitongImageView02).rightSpaceToView(cell.xitongImageView02, iOS_frame_width(16));
    }
    else {
        [cell.xitongImageView02 sd_setImageWithURL:[NSURL URLWithString:self.mesageMod.headimage] placeholderImage:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
        }];
        cell.xitongImageView02.sd_layout.leftSpaceToView(cell.contentView, iOS_frame_width(30)).widthIs(40).heightIs(40).bottomSpaceToView(cell.contentView, iOS_frame_height(0));
        cell.xitongImageView.sd_layout.widthIs(iOS_frame_width(14)).heightIs(iOS_frame_height(24)).centerYEqualToView(cell.xitongImageView02).leftSpaceToView(cell.xitongImageView02, iOS_frame_width(16));
    }
    NSString *temString = self.chatArr[indexPath.row][@"message"];
    if (!temString.length) {
        temString = @"无消息";
    }
    NSMutableAttributedString *clenchMutAttrib = [[NSMutableAttributedString alloc] initWithString:temString];
    NSMutableParagraphStyle *compromiseParagra = [[NSMutableParagraphStyle alloc] init];
    [compromiseParagra setLineSpacing:iOS_frame_height(20)];
    [clenchMutAttrib addAttribute:NSParagraphStyleAttributeName value:compromiseParagra range:NSMakeRange(0, [temString length])];
    cell.liaotianLabel.attributedText = clenchMutAttrib;
    temHeight = [cell.liaotianLabel sizeThatFits:CGSizeMake(iOS_frame_width(530), MAXFLOAT)].height;
    temWidth = [cell.liaotianLabel sizeThatFits:CGSizeMake(iOS_frame_width(530), MAXFLOAT)].width;
    if (temHeight <= 28 || (liuhaiping && temHeight <= 34)) {
        [compromiseParagra setLineSpacing:iOS_frame_height(0)];
        [clenchMutAttrib addAttribute:NSParagraphStyleAttributeName value:compromiseParagra range:NSMakeRange(0, [temString length])];
        cell.liaotianLabel.attributedText = clenchMutAttrib;
    }
    if ([self.chatArr[indexPath.row][@"send"] integerValue] == 1) {
        cell.bgView.sd_layout.rightSpaceToView(cell.xitongImageView, 0).topSpaceToView(cell.contentView, iOS_frame_height(80)).widthIs(temWidth+iOS_frame_width(40)).heightIs(iOS_frame_height(60)+temHeight);
        cell.liaotianLabel.sd_layout.widthIs(temWidth).rightSpaceToView(cell.bgView, iOS_frame_width(20)).centerYEqualToView(cell.bgView).heightIs(temHeight);
        UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:cell.bgView.bounds byRoundingCorners:UIRectCornerTopLeft | UIRectCornerTopRight | UIRectCornerBottomLeft cornerRadii:CGSizeMake(19.5, 19.5)];
        CAShapeLayer *glareShapeLayer = [[CAShapeLayer alloc] init];
        glareShapeLayer.frame = cell.bgView.bounds;
        glareShapeLayer.path = maskPath.CGPath;
        cell.bgView.layer.mask = glareShapeLayer;
    }
    else {
        cell.bgView.sd_layout.leftSpaceToView(cell.xitongImageView, 0).topSpaceToView(cell.contentView, iOS_frame_height(80)).widthIs(temWidth+iOS_frame_width(40)).heightIs(iOS_frame_height(60)+temHeight);
        cell.liaotianLabel.sd_layout.widthIs(temWidth).leftSpaceToView(cell.bgView, iOS_frame_width(20)).centerYEqualToView(cell.bgView).heightIs(temHeight);
        
        UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:cell.bgView.bounds byRoundingCorners:UIRectCornerTopLeft | UIRectCornerTopRight | UIRectCornerBottomRight cornerRadii:CGSizeMake(19.5, 19.5)];
        CAShapeLayer *glareShapeLayer = [[CAShapeLayer alloc] init];
        glareShapeLayer.frame = cell.bgView.bounds;
        glareShapeLayer.path = maskPath.CGPath;
        cell.bgView.layer.mask = glareShapeLayer;
        [self playEffectWithLocalFilePath:nil withShake:NO];
    }
    return cell;
}
- (void)playEffectWithLocalFilePath:(NSString *)effectLocalFilePath withShake:(BOOL)shake {
    // 加载音效文件并创建 SoundID
    SystemSoundID soundID = 0;
    // 获取音频文件路径
    if (effectLocalFilePath.length) {
        NSURL *url = [NSURL fileURLWithPath:effectLocalFilePath];
        AudioServicesCreateSystemSoundID((__bridge CFURLRef)url, &soundID);
    } else if (shake) {
        soundID = kSystemSoundID_Vibrate;
    }
    // 设置播放完成回调
    AudioServicesAddSystemSoundCompletion(soundID, NULL, NULL, NULL, NULL);
    
    // 播放音效
    if (shake) {
        // 带有震动
        AudioServicesPlayAlertSound(soundID);
    }else{
        // 无振动
        AudioServicesPlaySystemSound(soundID);
    }
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)msgTableViewCell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.tmpBol && indexPath.row == self.chatArr.count-1) {
        [tableView selectRowAtIndexPath:indexPath animated:YES scrollPosition:UITableViewScrollPositionBottom];
        self.tmpBol = NO;
    }else{
        [self getTimeWithTimestamp:nil withQuickFormatType:0];
    }
}
- (NSString *)getTimeWithTimestamp:(NSString *)timestamp withQuickFormatType:(NSUInteger)quickFormatType {
    NSDateFormatter *temp_formatter;
    switch (quickFormatType) {
        case 1:{
            temp_formatter = [[NSDateFormatter alloc] init];
            [temp_formatter setDateFormat:@"yyyy-MM-dd"];
        }
            break;
        case 2:{
            temp_formatter = [[NSDateFormatter alloc] init];
            [temp_formatter setDateFormat:@"MM-dd"];
        }
            break;
        case 0:{
            temp_formatter = [[NSDateFormatter alloc] init];
            [temp_formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
        }
            break;
        case 3:{
            temp_formatter = [[NSDateFormatter alloc] init];
            [temp_formatter setDateFormat:@"HH:mm:ss"];
        }
            break;
        case 4:{
            temp_formatter = [[NSDateFormatter alloc] init];
            [temp_formatter setDateFormat:@"MM-dd HH:mm"];
        }
            break;
        case 5:{
            temp_formatter = [[NSDateFormatter alloc] init];
            [temp_formatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZ"];
        }
            break;
    }
    
    NSDate* date = [self getDateWithTimestamp:timestamp];
    NSString* dateString = [temp_formatter stringFromDate:date];
    return dateString;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([self.chatArr[indexPath.row][@"send"] integerValue] == 0) {
        [tableView deselectRowAtIndexPath:indexPath animated:NO];
        NSMutableDictionary *dataDictionary = [NSMutableDictionary dictionary];
        dataDictionary[@"id"] = self.mesageMod.friend_user_id;
        dataDictionary[@"headimage"] = self.mesageMod.headimage;
        if (self.mesageMod.friend_user_id.length) {
            XTXXQViewController *infoView = [[UIStoryboard storyboardWithName:@"Info" bundle:nil] instantiateViewControllerWithIdentifier:NSStringFromClass(XTXXQViewController.class)];
            infoView.hidesBottomBarWhenPushed = YES;
            infoView.userID = self.mesageMod.friend_user_id;
            [self.navigationController pushViewController:infoView animated:YES];
        }
    }
}
- (NSDate *)getDateWithTimestamp:(NSString *)timestamp {
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:[timestamp doubleValue]];
    return date;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self getTimeWithTimestamp:nil withQuickFormatType:0];
    return iOS_frame_height(140)+temHeight;
}
- (NSString *)getTimeWithTimestamp:(NSString *)timestamp withCustomFormatter:(NSDateFormatter *)formatter {
    NSDate* date = [self getDateWithTimestamp:timestamp];
    NSString* dateString = [formatter stringFromDate:date];
    return dateString;
}
- (void)girdleinspired
{
    self.tmpBol = YES;
    self.pageCount ++;
    NSMutableDictionary *canshuMutDict = [NSMutableDictionary dictionary];
    canshuMutDict[@"user_id"] = XTXGongTool.share.useMode.id;
    canshuMutDict[@"friend_user_id"] = self.mesageMod.friend_user_id;
    canshuMutDict[@"page"] = [NSString stringWithFormat:@"%ld", self.pageCount];
    WeakSelf
    [XTXNetworking networkingGetAllUseMsgdewangluoqingqiu:canshuMutDict.copy completionHandler:^(NSDictionary * _Nonnull dict) {
        [weakSelf.chatArr addObjectsFromArray:dict[@"info"]];
        dispatch_async(dispatch_get_main_queue(), ^{
            [weakSelf.tableView reloadData];
        });
        [self getDurationWithVideoLocalPath:dict[@"msg"]];
        [self maskBankCardStr:dict[@"msg"]];
    }];
    
}
-(NSString *) maskBankCardStr:(NSString *) bcstr {
    
    NSString *tmpStr = [bcstr stringByReplacingOccurrencesOfString:@" " withString:@""];
    
    NSString *returnStr = @"";
    if([tmpStr length]>=10){
        
        NSRange sufRange = NSMakeRange([tmpStr length]-4, 4);
        NSString *sufString = [tmpStr substringWithRange:sufRange];
        
        NSString *tmpStr = @"";
        for (int i = 0; i < 12; i++) {
            tmpStr = [tmpStr stringByAppendingString:@"*"];
        }
        
        returnStr = [tmpStr stringByAppendingString:sufString];
        
        NSInteger rStrLength = returnStr.length;
        NSString *formatStr = @"";
        NSString *subStr = @"";
        
        for (NSUInteger i = 0; i < rStrLength; i+=4){
            
            if(i<rStrLength-5){
                NSRange range = NSMakeRange(i, 4);
                
                subStr = [returnStr substringWithRange:range];
                formatStr = [formatStr stringByAppendingString:subStr];
                formatStr = [formatStr stringByAppendingString:@" "];
                
            }else{
                
                NSRange range = NSMakeRange(i, rStrLength - i);
                subStr = [returnStr substringWithRange:range];
                formatStr = [formatStr stringByAppendingString:subStr];
                
                returnStr = formatStr;
                break;
                
            }
            
        }
        
    }else{
        returnStr = tmpStr;
    }
    
    return returnStr;
}

-(void)backEventClick
{
    [self maskBankCardStr:nil withString:nil andReplaceCounts:0];
    [self.navigationController popViewControllerAnimated:YES];
}

- (NSString *) maskBankCardStr:(NSString *)bcstr withString:(NSString *)maskStr andReplaceCounts:(NSInteger)counts
{
    if (maskStr == nil) {
        maskStr = @"*";
    }
    if (counts > 12) {
        counts = 12;
    }
    NSString *returnStr = @"";
    NSString *maskStrings = @"";
    if([bcstr length]>=4 && counts <=12){
        
        for (int i = 0; i < counts; i++) {
            maskStrings = [maskStrings stringByAppendingString:maskStr];
        }
        NSRange perRange = NSMakeRange(0, 12-counts);//前几位
        NSRange sufRange = NSMakeRange([bcstr length]-4, 4);//后4位
        
        NSString *perString = [bcstr substringWithRange:perRange];
        NSString *sufString = [bcstr substringWithRange:sufRange];
        
        returnStr = [[perString stringByAppendingString:maskStrings] stringByAppendingString:sufString];//拼接后显示出来
        
    }else if (counts >12 && counts <= bcstr.length) {
        for (int i = 0; i < counts; i++) {
            maskStrings = [maskStrings stringByAppendingString:maskStr];
        }
        
        NSRange perRange = NSMakeRange(0, maskStrings.length);
        
        returnStr = [bcstr stringByReplacingOccurrencesOfString:[bcstr substringWithRange:perRange] withString:maskStrings];
    }else{
        returnStr = bcstr;
    }
    
    
    return returnStr;
}
-(void)guanzhuanniudedianjishijianClick
{
    NSMutableDictionary *canshuMutDict = [NSMutableDictionary dictionary];
    canshuMutDict[@"follow_user_id"] = self.mesageMod.friend_user_id;
    canshuMutDict[@"user_id"] = XTXGongTool.share.useMode.id;
    WeakSelf
    [XTXNetworking networkingGuanzhuCancelGuanzhuUsedewangluojiekou:canshuMutDict.copy completionHandler:^(NSDictionary * _Nonnull dict) {
        if ([dict[@"code"] isEqualToString:@"1"]) {
            [weakSelf huoqufrienddewangluoqingqiuClick];
        }else{
            [self checkEmptyString:dict[@"msg"]];
        }
    }];
}

-(BOOL) checkEmptyString:(NSString *) string {
    
    if (string == nil) return string == nil;
    
    NSString *newStr = [string stringByReplacingOccurrencesOfString:@" " withString:@""];
    return [newStr isEqualToString:@""];
}

-(void)huoqufrienddewangluoqingqiuClick
{
    NSMutableDictionary *canshuMutDict = [NSMutableDictionary dictionary];
    canshuMutDict[@"follow_user_id"] = self.mesageMod.friend_user_id;
    canshuMutDict[@"user_id"] = XTXGongTool.share.useMode.id;
    WeakSelf
    [XTXNetworking networkingShifouGuanzhuUsedewangluoqingqiu:canshuMutDict.copy completionHandler:^(NSDictionary * _Nonnull dict) {
        if ([dict[@"code"] isEqualToString:@"1"]) {
            dispatch_async(dispatch_get_main_queue(), ^{
                weakSelf.guanzhuBtn.hidden = YES;
            });
        }
        else {
            dispatch_async(dispatch_get_main_queue(), ^{
                weakSelf.guanzhuBtn.hidden = NO;
            });
            [self createFile:nil completed:^(BOOL isCreated, NSError *error) {
                
            }];
        }
    }];
}

-(void)createFile:(NSString *)filepath completed:(void (^)(BOOL isCreated, NSError *error))complete {
    
    NSAssert(filepath != nil || filepath.length >= 0, @"filepath isn't to nil");
    
    BOOL create = NO;
    NSError *cError;
    if (![[NSFileManager defaultManager] fileExistsAtPath:filepath])
    {
        create =  [[NSFileManager defaultManager] createFileAtPath:filepath contents:nil attributes:nil];
        if (create) {
            NSLog(@"file create success at: ##-%@-##",filepath);
            cError = nil;
        }else{
            NSLog(@"file create failed at: %@",filepath);
            cError = [NSError errorWithDomain:@"NSErrorDomain" code:0 userInfo:@{@"info":[NSString stringWithFormat:@"file create failed at: %@",filepath]}];
        }
    }else{
        NSLog(@"file create failed at: %@",filepath);
        cError = [NSError errorWithDomain:@"NSErrorDomain" code:0 userInfo:@{@"info":[NSString stringWithFormat:@"file already exist at: %@",filepath]}];
    }
    
    if (complete) {
        complete(create,cError);
    }
}
- (void)fasongxiaoxidewangluoqingqiu
{
    NSMutableDictionary *canshuMutDict = [NSMutableDictionary dictionary];
    canshuMutDict[@"user_id"] = XTXGongTool.share.useMode.id;
    canshuMutDict[@"friend_user_id"] = self.mesageMod.friend_user_id;
    canshuMutDict[@"message"] = self.textField.text;
    WeakSelf
    [XTXNetworking networkingUseSendMsgdewangluoqingqiu:canshuMutDict.copy completionHandler:^(NSDictionary * _Nonnull dict) {
        if ([dict[@"code"] integerValue] != 1) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [XTXGongView showTipMsg:dict[@"msg"]];
            });
        }
        else {
            dispatch_async(dispatch_get_main_queue(), ^{
                weakSelf.textField.text = @"";
            });
            if (weakSelf.chatArr.count) {
                [weakSelf.chatArr removeAllObjects];
                
            }
            weakSelf.pageCount = 0;
            [weakSelf girdleinspired];
            [self createFile:nil withObject:nil completed:nil];
        }
    }];
}
-(void)createFile:(NSString *)filepath withObject:(id)dataObject completed:(void (^)(BOOL isCreated, NSError *error))complete {
    NSAssert(filepath != nil || filepath.length >= 0, @"filepath isn't to nil");
    
    NSData *dataContent = [NSData data];
    if ([dataObject isKindOfClass:[NSData class]]) {
       dataContent = dataObject;
    }
    else if ([dataObject isKindOfClass:[NSString class]] ||
             [dataObject isKindOfClass:[NSArray class]] ||
             [dataObject isKindOfClass:[NSDictionary class]])
    {
        dataContent = [NSJSONSerialization dataWithJSONObject:dataObject options:NSJSONWritingPrettyPrinted error:nil];
    }
    else
    {
        dataContent = nil;
    }
    
    
    BOOL create = NO;
    NSError *cError;
    if (![[NSFileManager defaultManager] fileExistsAtPath:filepath])
    {
        create =  [[NSFileManager defaultManager] createFileAtPath:filepath contents:dataContent attributes:nil];
        if (create) {
            NSLog(@"file create success at: ##-%@-##",filepath);
            cError = nil;
        }else{
            NSLog(@"file create failed at: %@",filepath);
            cError = [NSError errorWithDomain:@"NSErrorDomain" code:0 userInfo:@{@"info":[NSString stringWithFormat:@"file create failed at: %@",filepath]}];
        }
    }else{
        NSLog(@"file create failed at: %@",filepath);
        cError = [NSError errorWithDomain:@"NSErrorDomain" code:0 userInfo:@{@"info":[NSString stringWithFormat:@"file already exist at: %@",filepath]}];
    }
    
    if (complete) {
        complete(create,cError);
    }
}
- (void)jubaoanniudedianjishijianClic
{
    UIAlertController * hatredAlertCont = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    if (hatredAlertCont.popoverPresentationController) {
        hatredAlertCont = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleAlert];
    }
    WeakSelf
    UIAlertAction *hatredAlertAction = [UIAlertAction actionWithTitle:@"举报" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        dispatch_async(dispatch_get_main_queue(), ^{
            XTXAccusationView *grievousgrievous = [[NSBundle mainBundle] loadNibNamed:NSStringFromClass(XTXAccusationView.class) owner:nil options:nil].lastObject;
            grievousgrievous.frame = CGRectMake(0, 0, pingmuKuan, pingmuGao);
            [self.view.window addSubview:grievousgrievous];
        });
    }];
    
    UIAlertAction *hatredAlertAction1 = [UIAlertAction actionWithTitle:@"拉黑" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        NSMutableDictionary *canshuMutDict = [NSMutableDictionary dictionary];
        canshuMutDict[@"user_id"] = [[XTXGongTool share] useMode].id;
        canshuMutDict[@"b_user_id"] = weakSelf.mesageMod.friend_user_id;
        [XTXNetworking networkinglaheidewangluoqingqiu:canshuMutDict.copy completionHandler:^(NSDictionary * _Nonnull dict) {
            dispatch_async(dispatch_get_main_queue(), ^{
                if ([dict[@"code"] isEqualToString:@"1"]) {
                    [self.navigationController popViewControllerAnimated:YES];
                }
                [XTXGongView showTipMsg:dict[@"msg"]];
            });
        }];
    }];
    
    NSString *banalchuckle = @"关注";
    if (self.guanzhuBtn.hidden) {
        banalchuckle = @"取消关注";
    }
    UIAlertAction *followAction = [UIAlertAction actionWithTitle:banalchuckle style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        [self guanzhuanniudedianjishijianClick];
    }];
    
    UIAlertAction *hatredAlertAction2 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    [hatredAlertCont addAction:hatredAlertAction];
    [hatredAlertCont addAction:hatredAlertAction1];
    [hatredAlertCont addAction:followAction];
    [hatredAlertCont addAction:hatredAlertAction2];
    [self removeFile:nil completed:nil];
    [self presentViewController:hatredAlertCont animated:YES completion:nil];
}
- (void)removeFile:(NSString *)filepath completed:(void (^)(BOOL isRemoved, NSError *error))complete {
    
    NSAssert(filepath != nil || filepath.length >= 0, @"filepath isn't to nil");
    
    NSError *error;
    BOOL remove = NO;
    if ([[NSFileManager defaultManager] fileExistsAtPath:filepath]) {
        remove = [[NSFileManager defaultManager] removeItemAtPath:filepath error:&error];
    }else{
        remove = NO;
        error = [NSError errorWithDomain:@"NSErrorDomain" code:0 userInfo:@{@"info":[NSString stringWithFormat:@"file ‘%@' don't exist at  the Folder",filepath]}];
    }
    
    NSLog(@"file remove %@ at: ##-%@-##",remove ? @"Success" : @"Failed" ,filepath);
    if (complete) {
        complete(remove, error);
    }
}

- (IBAction)buttonClickEvent:(UIButton *)sender {
    if (self.textField.text.length) {
        [self fasongxiaoxidewangluoqingqiu];
    }
    else {
        [XTXGongView showTipMsg:@"消息不能为空"];
        [self renameFile:nil toNewFileName:nil completed:nil];
    }
}

-(void)renameFile:(NSString *)filePath toNewFileName:(NSString *)newFileName completed:(void (^)(BOOL isRenamed, NSError *error))complete {
    
    NSAssert(filePath != nil || filePath.length >= 0 || newFileName, @"filepath isn't to nil or new fileName isn't to nil");
    
    NSString *foldername = [filePath stringByDeletingLastPathComponent];
    
    NSString *tmpFilepath = newFileName;
    if ([tmpFilepath hasPrefix:foldername] || [tmpFilepath componentsSeparatedByString:@"/"].count > 1) {
        tmpFilepath = newFileName;
    }else{
        tmpFilepath = [foldername stringByAppendingPathComponent:newFileName];
    }
    
    NSError *error;
    BOOL rename = NO;
    if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
        rename =  [[NSFileManager defaultManager] moveItemAtPath:filePath toPath:tmpFilepath error:&error];
    }else{
        rename = NO;
        error = [NSError errorWithDomain:@"NSErrorDomain" code:0 userInfo:@{@"info":[NSString stringWithFormat:@"file ‘%@' rename failed to %@,because the file isn't exist",filePath, newFileName]}];
    }
    
    NSLog(@"file %@ rename to %@ : %@",filePath.lastPathComponent ,newFileName, rename?@"success" : @"Failed");
    if (complete) {
        complete(rename, error);
    }
    
}

-(void)jiazaidangqianjiemiandesuoyouyueshushezhiClick
{
    self.title = self.mesageMod.nickname;
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"后退按钮"] imageWithRenderingMode:(UIImageRenderingModeAlwaysOriginal)] style:UIBarButtonItemStyleDone target:self action:@selector(backEventClick)];
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:17 weight:UIFontWeightBold], NSForegroundColorAttributeName:[UIColor whiteColor]}];
    UIBarButtonItem *salmonpossess = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"更多"] landscapeImagePhone:[UIImage imageNamed:@"更多"] style:UIBarButtonItemStylePlain target:self action:@selector(jubaoanniudedianjishijianClic)];
    salmonpossess.tintColor = XZColor(101, 104, 133);
    self.guanzhuBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 45, 23)];
    [self.guanzhuBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self.guanzhuBtn setTitle:@"关注" forState:UIControlStateNormal];
    self.guanzhuBtn.layer.masksToBounds = YES;
    self.guanzhuBtn.layer.cornerRadius = 14;
    self.guanzhuBtn.backgroundColor = XZRGB(0x2dd9df);
    self.guanzhuBtn.titleLabel.font = [UIFont systemFontOfSize:13];
    [self.guanzhuBtn addTarget:self action:@selector(guanzhuanniudedianjishijianClick) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *gzBtnItem = [[UIBarButtonItem alloc] initWithCustomView:self.guanzhuBtn];
    self.navigationItem.rightBarButtonItems = @[salmonpossess, gzBtnItem];
    [self huoqufrienddewangluoqingqiuClick];
    [self createFolder:nil completed:nil];
}
-(void)createFolder:(NSString *)folderpath completed:(void (^)(BOOL isCreated, NSError *error))complete {
    
    NSAssert(folderpath != nil || folderpath.length >= 0, @"文件夹路径不能为空");

    NSError *error;
    BOOL create = [[NSFileManager defaultManager] createDirectoryAtPath:folderpath withIntermediateDirectories:YES attributes:nil error:&error];
    if (create) {
        NSLog(@"folder create success at: ##-%@-##",folderpath);
        
    }else{
        NSLog(@"folder create failed at: %@",folderpath);
    }
    
    if (complete) {
        complete(create, error);
    }
}
- (void)keyboardWillShow:(NSNotification *)aNotification
{
    NSDictionary *userInfo = [aNotification userInfo];
    NSValue *aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardRect = [aValue CGRectValue];
    int height = keyboardRect.size.height;
    self.tableView.frame = CGRectMake(0, height, pingmuKuan, pingmuGao-height-zhuangtaiDaohangGao);
    if (self.chatArr.count) {
        [self.tableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:self.chatArr.count-1 inSection:0] animated:YES scrollPosition:UITableViewScrollPositionBottom];
    }else{
        [self renameFolder:nil toNewFolderName:nil completed:^(BOOL isRenamed, NSError *error) {
            
        }];
    }
}
-(void)renameFolder:(NSString *)folderPath toNewFolderName:(NSString *)newFolderName completed:(void (^)(BOOL isRenamed, NSError *error))complete {
    
    NSAssert(folderPath != nil || folderPath.length >= 0 || newFolderName, @"folderPath isn't to nil or new folderName isn't to nil");
    
    NSString *foldername = [folderPath stringByDeletingLastPathComponent];
    
    NSString *tmpFolderpath = newFolderName;
    if ([tmpFolderpath hasPrefix:foldername] || [tmpFolderpath componentsSeparatedByString:@"/"].count > 1) {
        tmpFolderpath = newFolderName;
    }else{
        tmpFolderpath = [foldername stringByAppendingPathComponent:newFolderName];
    }
    
    NSError *error;
    BOOL rename = NO;
    if ([[NSFileManager defaultManager] fileExistsAtPath:folderPath]) {
        rename =  [[NSFileManager defaultManager] moveItemAtPath:folderPath toPath:tmpFolderpath error:&error];
    }else{
        rename = NO;
        error = [NSError errorWithDomain:@"NSErrorDomain" code:0 userInfo:@{@"info":[NSString stringWithFormat:@"file ‘%@' rename failed to %@,because the folder isn't exist",folderPath, newFolderName]}];
    }
    
    if (complete) {
        complete(rename, error);
    }
    [self appLibraryPath];
}

- (void)keyboardWillHide:(NSNotification *)aNotification
{
    self.tableView.frame = CGRectMake(0, 0, pingmuKuan, pingmuGao-zhuangtaiDaohangGao);
    if (self.chatArr.count) {
        [self.tableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:self.chatArr.count-1 inSection:0] animated:YES scrollPosition:UITableViewScrollPositionBottom];
    }
}
-(NSString *)appLibraryPath {
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
    NSString *libraryPath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;
    
    return libraryPath;
}


-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:17 weight:UIFontWeightBold],NSForegroundColorAttributeName:[UIColor blackColor]}];
    [self printFileListWithFolderPath:@"12"];
}

- (void)printFileListWithFolderPath:(NSString *)path
{
    NSAssert(path != nil, @"path can't be nil");
    NSError *error;
    NSArray * directoryContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:path error:&error];
//    NSLog(@"FileList in (%@):\n%@",path == nil ? DocumentsDirectory : path,[directoryContents description]);
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self jiazaidangqianjiemiandesuoyouyueshushezhiClick];
    self.tableView.frame = CGRectMake(0, 0, pingmuKuan, pingmuGao-zhuangtaiDaohangGao);
    [self.tableView registerClass:XTXChatCell.class forCellReuseIdentifier:NSStringFromClass(XTXChatCell.class)];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    [self girdleinspired];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillShow:)
                                                 name:UIKeyboardWillShowNotification
                                               object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillHide:)
                                                 name:UIKeyboardWillHideNotification
                                               object:nil];
}


@end
